package io.iamting93.gateway.filter;

import io.iamting93.api.UserApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author boting.guo
 * @date 2021/12/6 11:10
 */

@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @DubboReference
    private UserApi userApi;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String requestUrl = request.getPath().pathWithinApplication().value();
        if (requestUrl.contains("/login") || requestUrl.contains("/register") || requestUrl.contains("/code")) {
            // 放过登录、注册和验证码相关的请求
            return chain.filter(exchange);
        }
        HttpCookie token = request.getCookies().getFirst("token");

        if (token != null) {
            // 验证token
            String t = token.getValue();
            String email = userApi.info(t);
            if(email != null) {
                log.info("接收来自用户" + email + "的请求");
                return chain.filter(exchange);
            }
        }


        // 跳转到登录页面
        log.info("token为空或不合法，跳转到登录页面");
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set(HttpHeaders.LOCATION, "http://www.test.com/static/login.html");
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
